package com.north.light.androidxvp.network


import android.app.Activity
import com.north.light.androidxvp.constant.NetConstants
import com.north.light.androidxvp.network.base.NetInterceptor
import com.north.light.androidxvp.network.base.RetryWithDelay
import com.north.light.androidxvp.network.base.TokenException
import com.north.light.androidxvp.network.bean.BaseResult
import com.north.light.androidxvp.ui.main.MainActivity
import com.north.light.libnetwork.base.BaseNetWork
import com.north.light.libnetwork.bean.BaseCode
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableTransformer
import io.reactivex.rxjava3.schedulers.Schedulers
import okhttp3.Interceptor

/**
 * create by lzt
 * data 2019/12/21
 * 网络请求工具类
 */
class NetWorkUtils : BaseNetWork() {
    val netWorkApi: NetWorkApi

    private object SingleHolder {
        internal val mInstance = NetWorkUtils()
    }

    init {
        init(NetConstants.BASE_URL)
        netWorkApi = retrofit!!.create(NetWorkApi::class.java)
    }

    /**
     * 线程切换
     * token刷新
     * 基类拦截处理，若后续结果还是返回401，则直接返回到登录页面
     *
     * @return
     */
    fun <T : BaseCode> getScheduler(): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .flatMap { t ->
                        if (t.code == NetConstants.CODE_TOKEN_ERROR.toString()
                                || t.code == NetConstants.CODE_TOKEN_ERROR2.toString()) {
                            Observable.error(TokenException())
                        } else Observable.just(t)
                    }.retryWhen(RetryWithDelay(3, 1000))
        }
    }

    companion object {
        private val TAG = NetWorkUtils::class.java.name

        val instance: NetWorkUtils
            get() = SingleHolder.mInstance
    }


//    override fun <T : Interceptor> interceptor(): T {
//        return NetInterceptor() as T
//    }

    override fun interceptor(): Interceptor {
        return NetInterceptor()
    }

    override fun timeOut(): Int {
        return 10
    }
}
